<script setup lang="ts">
import {onBeforeUnmount, onMounted, reactive, ref, shallowRef} from "vue";
import {QuestionPublishReq} from "@/api/qa/types";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {IDomEditor} from '@wangeditor/editor'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getCategoryTree, publishNewQuestion, saveQuestionDraft} from "@/api/qa";
import type {FormInstance, FormRules} from 'element-plus'
import {transformElTree} from "@/utils/tree";
import { useRouter } from 'vue-router'

const router = useRouter()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const isFocused = ref(false)
const questionFormRef = ref<FormInstance>()

const questionForm = reactive<QuestionPublishReq>({
  title: '',
  summary: '',
  content: '',
  categoryId: null
})

const categoryTree = ref([]);

const questionFormRules = reactive<FormRules<QuestionPublishReq>>({
  title: [
    {required: true, message: '请填写问题标题', trigger: 'blur'},
    {min: 1, max: 100, message: '长度请限制在1-100', trigger: 'blur'},
  ],
  content: [
    {required: true, message: '请填写问题详情', trigger: 'blur'},
    {min: 10, max: 2000, message: '长度请限制在10-2000', trigger: 'blur'},
  ],
  categoryId: [
    {required: true, message: '请选择分类', trigger: 'change'},
  ]
})

const handleEditorCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const onEditorMaxLength = (editor: IDomEditor) => {
  ElMessageBox.alert('超出最大长度限制', '提示', {
    confirmButtonText: '知道了'
  })
}
const loadCategoryTreeSelect = () => {
  getCategoryTree().then(result => {
    categoryTree.value = transformElTree(result)
  })
}

const saveDraft = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      saveQuestionDraft(questionForm).then((result) => {
        ElMessage({
          type: 'success',
          message: "保存成功"
        })
      })
    }
  })
}

const publish = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      //摘要截取前200字符
      questionForm.summary = editorRef.value.getText().slice(0, 200)
      publishNewQuestion(questionForm).then((result) => {
        router.replace({ path: '/questions/detail', query: { id: Number(result) }})
        ElMessage({
          type: 'success',
          message: "发布成功"
        })
      })
    }
  })
}

onMounted(() => {
  loadCategoryTreeSelect()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor != null) {
    setTimeout(()=> editor.destroy(), 200)
  }
})
</script>

<template>
  <div class="w-full h-full overflow-auto bg-white-soft">
    <div class="mt-6">
      <div class="ui FHContainer">
        <div class="FHMain">
          <div class="FHContent flex flex-row">
            <div class="content">
              <h1 class="text-3xl font-bold text-center mb-8">发布新问题</h1>
              <el-form class="p-6" ref="questionFormRef" :model="questionForm" label-width="auto"
                       label-position="top" size="large"
                       :rules="questionFormRules">
                <el-form-item label="问题标题" prop="title">
                  <el-input v-model="questionForm.title" placeholder="请输入问题标题" autofocus/>
                </el-form-item>
                <el-form-item label="分类" prop="categoryId" label-position="left">
                  <el-tree-select
                      v-model="questionForm.categoryId"
                      :data="categoryTree"
                      :render-after-expand="false"
                      style="width: 240px"
                      placeholder="请选择分类"
                  />
                </el-form-item>
                <el-form-item label="问题详情" prop="content">
                  <div class="rounded-lg overflow-hidden" style="border: 1px solid var(--el-border-color)"
                       :class="{'input-focus': isFocused}">
                    <Toolbar
                        style="border-bottom: 1px solid var(--el-border-color)"
                        :editor="editorRef"
                        :defaultConfig="{}"
                        mode="default"
                    />
                    <Editor
                        style="height: 500px; overflow-y: hidden;"
                        v-model="questionForm.content"
                        :defaultConfig="{placeholder: '请输入内容...', autoFocus: false, maxLength: 2000}"
                        mode="default"
                        @onCreated="handleEditorCreated"
                        @onFocus="isFocused = true"
                        @onBlur="isFocused = false"
                        @onMaxLength="onEditorMaxLength"
                    />
                  </div>
                </el-form-item>
                <!-- 提交按钮 -->
                <div class="flex justify-end">
                  <el-button @click="saveDraft(questionFormRef)">保存草稿</el-button>
                  <el-button type="primary" @click="publish(questionFormRef)">发布</el-button>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
.input-focus {
  border-color: var(--el-color-primary) !important;
}
</style>